import Toast from 'tdesign-miniprogram/toast/index';
import Log from '../../utils/log';
import commondUtil from '../../utils/commondUtil';
import validUtil from '../../utils/validUtil';
import Login from '../../api/modules/login';
import User from '../../api/modules/user';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    avatarUrl: '/static/images/user.png',

    updateDialogShowFlag: false,
    updateType: '',
    updateTypeName: '',
    updateInput: '',
    verificationCode: '',
    passwordRepeat: '',

    sendVerificationCodeText: '发送验证码',
    isCountingDown: false,
    countdown: 60,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    // 用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (commondUtil.isEmpty(userInfo)) {
      return;
    }
    this.setData({
      userInfo
    });
    // 头像
    const avatarUrl = wx.getStorageSync('avatarUrl:' + userInfo.id);
    if (commondUtil.isNotBlank(avatarUrl)) {
      this.setData({
        avatarUrl
      });
    }
  },

  onChooseAvatar(e) {
    if (commondUtil.isEmpty(this.data.userInfo)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '用户信息为空!请先登录',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    const avatarUrl = e.detail.avatarUrl;
    this.setData({
      avatarUrl
    });
    wx.setStorageSync('avatarUrl:' + this.data.userInfo.id, avatarUrl);
  },

  showUserInfoDialog(e) {
    const user = this.data.userInfo;
    if (commondUtil.isEmpty(user)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '用户信息为空!请先登录',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    const updateType = e.currentTarget.id;
    let updateTypeName = '';
    switch (updateType) {
      case 'email':
        updateTypeName = '邮箱';
        break;
      case 'password':
        updateTypeName = '密码';
        break;
      default:
        return;
    }
    this.setData({
      updateDialogShowFlag: true,
      updateType: updateType,
      updateTypeName: updateTypeName,
      [`${updateType}Input`]: user[updateType],
    });
  },
  userInfoDialogConfirm() {
    const updateType = this.data.updateType;
    const newValue = this.data.updateInput;
    const verificationCode = this.data.verificationCode;
    if (commondUtil.isBlank(verificationCode)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '验证码为空！',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    if (!validUtil.checkMinLength(verificationCode, 6)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '验证码有误！',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    if (commondUtil.isBlank(newValue)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: `新${this.data.updateTypeName}为空！`,
        theme: 'warning',
        direction: 'column',
      });
      return;
    }
    let apiName;
    switch (updateType) {
      case 'email':
        if (!validUtil.isEmail(newValue)) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '邮件格式错误！',
            theme: 'warning',
            direction: 'column',
          });
          return;
        }
        apiName = 'updateEmail';
        break;
      case 'password':
        if (!validUtil.checkMinLength(newValue, 6) || !validUtil.checkMaxLength(newValue, 30)) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '密码校验失败!(6~30位)',
            theme: 'warning',
            direction: 'column',
          });
          return;
        }
        if (this.data.passwordRepeat !== newValue) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '两次输入的密码不一致！',
            theme: 'warning',
            direction: 'column',
          });
          return;
        }
        apiName = 'updatePassword';
        break;
      default:
        return;
    }
    User[apiName]({
      code: verificationCode,
      [updateType]: newValue
    }).then(resp => {
      if (!resp?.data) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '修改失败！',
          theme: 'error',
          direction: 'column',
        });
        return;
      }

      Toast({
        context: this,
        selector: '#t-toast',
        message: '修改成功',
        theme: 'success',
        direction: 'column',
      });
      if (updateType !== 'password') {
        const newUserInfo = this.data.userInfo;
        newUserInfo[updateType] = newValue;
        wx.setStorageSync('userInfo', newUserInfo);
        this.setData({
          userInfo: newUserInfo,
        });
      }
      this.userInfoDialogClose();
    }).catch(e => {
      Log.errorAll("修改用户信息失败！", e);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '修改失败！',
        theme: 'error',
        direction: 'column',
      });
    });
  },
  userInfoDialogClose() {
    if (commondUtil.isNotEmpty(this.data.intervalId)) {
      clearInterval(this.data.intervalId);
    }
    this.setData({
      updateDialogShowFlag: false,
      verificationCode: '',
      isCountingDown: false,
      intervalId: null,
      sendVerificationCodeText: '发送验证码',
      updateType: '',
      updateInput: '',
      passwordRepeat: '',
    });
  },

  onLogout() {
    if (commondUtil.isEmpty(this.data.userInfo)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '用户信息为空!请先登录',
        theme: 'warning',
        direction: 'column',
      });
      return;
    }


    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (data) => {
        if (data.cancel || !data.confirm) {
          return;
        }

        Login.logout({
          username: this.data.userInfo.username
        }).then((resp) => {
          if (!resp.data) {
            Toast({
              context: this,
              selector: '#t-toast',
              message: resp.message ? resp.message : '退出登录失败！',
              theme: 'error',
              direction: 'column',
            });
            return;
          }
          wx.removeStorageSync('refreshToken');
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          Toast({
            context: this,
            selector: '#t-toast',
            message: '已退出登录',
            theme: 'success',
            direction: 'column',
          });
          this.jumpLoginPage();
        });
      }
    });
  },

  jumpLoginPage() {
    wx.redirectTo({
      url: '/pages/login/login',
      fail: e => {
        Log.warnAll("登陆超时，跳转到登录页失败！", e)
      },
    });
  },
  sendVerificationCode() {
    if (this.data.isCountingDown) {
      return;
    }

    // 发送验证码请求
    User.sendVerificationCode().then(resp => {
      if (!resp?.data) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: resp?.message ? resp.message : '发送验证码失败',
          theme: 'error',
          direction: 'column',
        });
        return;
      }
      this.setData({
        isCountingDown: true,
        countdown: 60,
        sendVerificationCodeText: `${this.data.countdown} 秒后重新发送`
      });
      this.startCountdown();
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '发送验证码失败',
        theme: 'error',
        direction: 'column',
      });
      Log.infoAll("发送验证码失败", e);
    });
  },
  startCountdown() {
    let countdown = this.data.countdown;
    const intervalId = setInterval(() => {
      countdown -= 1;
      this.setData({
        countdown,
        sendVerificationCodeText: `${countdown} 秒后重新发送`
      });
      if (countdown <= 0) {
        clearInterval(intervalId);
        this.setData({
          isCountingDown: false,
          intervalId: null,
          sendVerificationCodeText: '发送验证码'
        });
      }
    }, 1000);
    this.setData({
      intervalId
    });
  },

})